package com.suncaper.shop.service;


import com.suncaper.shop.domain.Product;
import com.suncaper.shop.domain.ProductExample;
import com.suncaper.shop.domain.User;
import com.suncaper.shop.mapper.ProductMapper;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    private ProductExample productExample;

    @Autowired
    JestClient jestClient;
    public List<Product> findAllByCid(int cid) {
        productExample = new ProductExample();

        productExample.createCriteria().
                andCidEqualTo(cid);

        return productMapper.selectByExample(productExample);
    }

    /**
     * 通过cid查找
     *
     * @param cid 类别
     * @return
     */
    public List<Product> findByCid(int cid) {

        productExample = new ProductExample();
        productExample.createCriteria().
                andCidEqualTo(cid);

        List<Product> pList = productMapper.selectByExample(productExample);
        return pList;
    }

    public void createViewToIndex(Integer i, Integer length, Model model) {
        Random ran = new Random();
        int ranNumber = ran.nextInt(3);
        for (int j = i; j < i + length; j++) {
            model.addAttribute("Cid" + j, findByCid(j).subList(ranNumber, ranNumber + 2));
        }
    }

    /**
     * 通过pid查找
     *
     * @param pid 产品id
     * @return
     */

    @Cacheable(value = {"product"})
    public Product findByPid(int pid) {
        productExample = new ProductExample();
        productExample.createCriteria().
                andPidEqualTo(pid);
        List<Product> productList = productMapper.selectByExample(productExample);
        Product product = productList.get(0);
        return product;
    }

    /**
     * 传入参数
     *
     * @param i 哪个大类
     * @return
     */
    public List<Product> findByHot(int i) {
        productExample = new ProductExample();
        productExample.setOrderByClause("is_hot desc");
        productExample.createCriteria().andIsHotGreaterThanOrEqualTo(1)
                .andCidBetween(i, i + 9);
        List<Product> products = productMapper.selectByExample(productExample);
        List<Product> sub = products.subList(0, 5);
        return sub;
    }

    /**
     * 相似查找
     *
     * @param i
     * @return
     */
    public List<Product> findSimilar(int i) {

        productExample = new ProductExample();
        productExample.createCriteria().andCidEqualTo(i);
        List<Product> productList = productMapper.selectByExample(productExample);
        if (productList.size() < 5) {
            return productList;
        } else {
            return productList.subList(0, 5);
        }
    }

    /**
     * 查找对应商家的所有物品
     */
    public List<Product> findAllByuid(HttpSession session) {
        productExample = new ProductExample();
        User userInfo = (User) session.getAttribute("userInfo");
        productExample.createCriteria().andUidEqualTo(userInfo.getId());
        List<Product> list = productMapper.selectByExample(productExample);
        session.setAttribute("productList", list);
        return list;
    }

    /**
     * 查找所有的物品
     *
     * @return
     */
    public List<Product> findAll() {
        productExample = new ProductExample();

        List<Product> list = productMapper.selectByExample(productExample);
        return list;
    }

    /**
     * 查找所有热门商品
     *
     * @return
     */
    public List<Product> findAllByHot() {
        productExample = new ProductExample();
        productExample.setOrderByClause("is_hot desc");
        productExample.createCriteria().andIsHotGreaterThanOrEqualTo(1);
        return productMapper.selectByExample(productExample).subList(0, 5);
    }

    /**
     * 返回按某一模块建立。
     *
     * @param factor
     * @param descOrasc
     * @return
     */
    public List<Product> findByFactor(String factor, String descOrasc) {
        productExample = new ProductExample();
        productExample.setOrderByClause(factor + " " + descOrasc);
        return productMapper.selectByExample(productExample);
    }

    /**
     * 价格查询
     *
     * @param min
     * @param max
     * @return
     */
    public List<Product> FilterByMoney(Double min, Double max) {
        productExample = new ProductExample();
        productExample.createCriteria().andShopPriceBetween(min, max);
        return productMapper.selectByExample(productExample);
    }

    /**
     * 折扣查询
     *
     * @return
     */
    public List<Product> findBydeals() {
        productExample = new ProductExample();
        productExample.setOrderByClause("deals desc");
        productExample.createCriteria().andDealsGreaterThanOrEqualTo(100.00);
        return productMapper.selectByExample(productExample);
    }

    /**
     * 模糊查询
     *
     * @param name
     * @return
     */
    public List<Product> findByname(String name, Integer cid) {
        productExample = new ProductExample();
        System.out.println(cid);
        if (cid != null) {
            productExample.createCriteria().andPnameLike('%' + name + '%').andCidBetween(cid, cid + 9);
            ProductExample productExample2 = new ProductExample();
            productExample2.createCriteria().andDescriptionLike('%' + name + '%').andCidBetween(cid, cid + 9);
            List<Product> products = productMapper.selectByExample(productExample);
            List<Product> products1 = productMapper.selectByExample(productExample2);

            List<Product> listAll = new ArrayList<Product>();
            listAll.addAll(products);
            listAll.addAll(products1);
            listAll = new ArrayList<Product>(new LinkedHashSet<>(listAll));
            List<Product> listAll1 = listAll;
            return listAll1;
        } else {
            productExample.createCriteria().andPnameLike('%' + name + '%');
            ProductExample productExample2 = new ProductExample();
            productExample2.createCriteria().andDescriptionLike('%' + name + '%');
            List<Product> products = productMapper.selectByExample(productExample);
            List<Product> products1 = productMapper.selectByExample(productExample2);

            List<Product> listAll = new ArrayList<Product>();
            listAll.addAll(products);
            listAll.addAll(products1);
            listAll = new ArrayList<Product>(new LinkedHashSet<>(listAll));
            List<Product> listAll1 = listAll;
            return listAll1;
        }
    }

    /**
     * 通过ElasticSearch查询
     * @param name
     * @return
     */
    public List<Product> elasticSearch(String name) throws IOException {

        String s="{\n" +
                "\t\"from\":0,\n" +
                "\t\"size\":20,\n" +
                "  \"query\": {\n" +
                "    \"bool\": {\n" +
                "      \"should\": [\n" +
                "        { \"match\": { \"pname\":  \""+name+"\" }},\n" +
                "        { \"match\": { \"description\": \""+name+"\"   }}\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";
        Search search = new Search.Builder(s).addIndex("shop").addType("product").build();

        SearchResult result = jestClient.execute(search);
        List<SearchResult.Hit<Product, Void>> hitList = result.getHits(Product.class);
        List<Product> productList=new ArrayList<Product>();
        for (SearchResult.Hit<Product, Void> hit : hitList) {
            Product source=hit.source;
            productList.add(source);
        }

        return productList;
    }

    /**
     * 入库存储
     *
     * @param product
     */
    public void saveByProduct(Product product) {

        productMapper.updateByPrimaryKey(product);
    }


    public boolean saveproduct(Product product) {
        Integer pid = product.getPid();
        productExample = new ProductExample();
        productExample.createCriteria().andPidEqualTo(pid);
        if (productMapper.selectByExample(productExample).size() == 0) {
            //代表没有存在
            product.setDeals(product.getMarketPrice() - product.getShopPrice());
            productMapper.updateByPrimaryKey(product);
            productMapper.insert(product);
            return true;
        }


        return false;
    }

    //删除商品表单数据
    public void delete(Product product) {
        Integer id = product.getPid();
        productExample = new ProductExample();
        productExample.createCriteria().andPidEqualTo(id);
        productMapper.deleteByPrimaryKey(id);
    }

    /**
     * 响应点击事件，增加热度
     *
     * @param pid
     */
    public void updateHot(Integer pid) {
        productExample = new ProductExample();
        productExample.createCriteria().andPidEqualTo(pid);
        List<Product> products = productMapper.selectByExample(productExample);
        if (products != null) {
            Product product = products.get(0);
            product.setIsHot(product.getIsHot() + 1);
            productMapper.updateByPrimaryKey(product);

        }
    }

    public List<Product> findByPage(Integer pagenumber, HttpSession session, Integer limit) {
        productExample = new ProductExample();
        productExample.createCriteria().andDealsGreaterThan(1.0);
        long count = productMapper.countByExample(productExample);
        session.setAttribute("dealcount", count);
        //得到所有的折扣商品
        List<Product> productList = productMapper.selectByExample(productExample);

        return count > pagenumber * limit ? productList.subList((pagenumber - 1) * limit, pagenumber * limit) : productList.subList((pagenumber - 1) * limit, (int) count - 2);
    }
}
